<?php
namespace app\api\controller;

use app\api\validate\UserValidate;
use app\common\controller\ApiAdminBase;
use think\facade\Request;
use app\common\model\User as UserModel;

class User extends ApiAdminBase
{

    use \app\api\traits\User;
    /**
     * @api {post} /user/list 会员列表
     * @apiName index
     * @apiGroup admin
     *
     * @apiParam {String{32位}}    admin_name        管理员名/管理员号码
     * @apiParam {String{32位}}    admin_password    管理员密码
     * @apiSuccessExample {json} 成功返回:
     *     {
     *         "data": [
     *         ],
     *         "code": 200,
     *         "msg": null
     *     }
     */
    public function index(Request $request){
        $input = $request::param();
        $per_page = $input['per_page']??10;
        $condition = [];
        $data = UserModel::getList($condition,[],['id desc'],$per_page);
        $data = $data ? $data->toArray() : [];
        $data['data'] = isset($data['data']) ? self::formatList($data['data']) : [];
        return $this->reply($data);

    }

    /**
     * @api {post} /user/add 添加会员
     * @apiName add
     * @apiGroup admin
     *
     * @apiParam {String{32位}}    admin_name        管理员名/管理员号码
     * @apiParam {String{32位}}    admin_password    管理员密码
     * @apiSuccessExample {json} 成功返回:
     *     {
     *         "data": [
     *         ],
     *         "code": 200,
     *         "msg": null
     *     }
     */
    public function add(Request $request){
        $input = $request::param();
        $validate = new UserValidate();
        $validate->checkAdd();
        if( !$validate->check($input) ){
            return $this->reply(null,1001,$validate->getError());
        }

        $admin_name = $input['admin_name'];
        $admin_password = $input['admin_password'];

        $count = UserModel::getCount(['admin_name'=>$admin_name]);
        if($count>0){
            return $this->reply(null,1103);
        }

        if(isset($input['admin_mobile'])){
            $count = UserModel::getCount(['admin_mobile'=>trim($input['admin_mobile'])]);
            if($count>0){
                return $this->reply(null,1103);
            }
        }

        $password = md5(md5($admin_password).$admin_password.config('app.private_key'));
        $model = new UserModel();
        $model->admin_name = $admin_name;
        $model->admin_password = $password;
        $model->admin_mobile = $input['admin_mobile']??'';
        $model->admin_avatar = $input['admin_avatar']??'';
        $model->is_super = intval($input['is_super']??0);
        $model->create_time = time();
        $model->update_time = $model->create_time;
        $id = $model->save();

        $code = 200;
        if($id<=0){
            $code = 1102;
        }
        return $this->reply(['id'=>$id],$code);
    }
}